<template>
  <!--  设备授权管理界面-->
  <div class="page">
    <!-- 条件筛选 -->
    <div class="page_filter">
      <el-cascader :options="monitorUnitTree" ref="cascader" clearable v-model="selectedSearchOptions" change-on-select
                   placeholder="请选择授权单位" @change="selectFromUnit"></el-cascader>
      <el-input v-model="form.caseCode" clearable placeholder="请输入设备编号">
        <template slot="prepend">设备编号</template>
      </el-input>
      <el-input v-model="form.queryString" clearable placeholder="请输入采集仪SN" :maxlength="30">
        <template slot="prepend">采集仪SN</template>
      </el-input>
      <el-button class="common_btn-defalut" icon="el-icon-search" @click="form.page=1;queryList()">搜索</el-button>
    </div>
    <div class="page_main">
      <el-tooltip class="item" effect="dark" content="使用我们平台的客户" placement="top-start">
        <el-button icon="el-icon-plus" @click.stop="handleAdd(5)" class="common_btn-small">授权新增</el-button>
      </el-tooltip>
      <el-tooltip class="item" effect="dark" content="只买设备不用平台" placement="top-start">
        <el-button icon="el-icon-plus" @click.stop="handleAdd(6)" class="common_btn-small">出售新增</el-button>
      </el-tooltip>
      <el-radio-group v-model="form.modelId" @change="form.page=1;queryList()" style="margin-bottom: 20px">
        <el-radio-button label="">所有型号</el-radio-button>
        <el-radio-button v-for="item in EnumEquipTypeList" :key="item.id" :label="item.id">
          {{item.name}}
        </el-radio-button>
      </el-radio-group>
      <!-- table -->
      <div class="common_btnBox">
        <i class="iconfont iconzongshu icon-size"></i>
        总数：{{form.total}}
      </div>
      <el-table :data="tableList" border>
        <el-table-column label="序号" fixed width="80">
          <template slot-scope="scope">
            {{getIndex(scope.$index)}}
          </template>
        </el-table-column>
        <el-table-column prop="caseCode" label="设备编号" min-width="130"></el-table-column>
        <el-table-column prop="sn" label="采集仪SN" min-width="165">
        </el-table-column>
        <el-table-column prop="batch" label="批次号" width="100">
        </el-table-column>
        <el-table-column prop="equipName" label="型号" width="120">
        </el-table-column>
        <el-table-column width="100" label="授权状态">
          <template slot-scope="scope">
            <el-tag size="mini" :style="scope.row.testStatus | equipStatusColor" style="color: white">
              {{scope.row.testStatusType}}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip prop="authCustomer" label="客户信息" min-width="280">
          <template slot-scope="scope">

            <button><i style="margin-right: 5px;font-size: 15px;color: #1990FE" class="el-icon-warning"
                       v-if="scope.row.authCustomer" @click="customerInfo(scope.row)"></i></button>
            {{scope.row.authCustomer}}
          </template>
        </el-table-column>
        <el-table-column prop="holePosition" label="关联的传感器" width="120" align="center">
          <template slot-scope="scope">
            <el-popover trigger="click" @show="showDevice(scope.row.id)" placement="right">
              <el-table :header-cell-style="{background:'#1990FE !important'}" border stripe :data="tableData"
                        style="width: 100%">
                <el-table-column prop="code" label="编码" width="130">
                </el-table-column>
                <el-table-column prop="typeName" label="类型" width="100">
                </el-table-column>
                <el-table-column prop="modelName" label="型号">
                </el-table-column>
              </el-table>
              <div slot="reference" class="name-wrapper">
                <i class="el-icon-data-analysis s-icon"></i>
              </div>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column prop="authTime" label="授权时间" width="170">
          <template slot-scope="scope">
            {{scope.row.authTime|formatTimer()}}
          </template>
        </el-table-column>
        <el-table-column prop="updateTime" label="更新时间" width="170">
          <template slot-scope="scope">
            {{scope.row.updateTime|formatTimer()}}
          </template>
        </el-table-column>
        <el-table-column prop="operator" label="操作人" width="120">
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="120">
          <template slot-scope="scope">
            <button v-if="scope.row.testStatus === 5" slot="reference" class="btn_delete"
                    @click="cancelAuth(scope.row)">取消授权
            </button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页器 -->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="form.page"
                     :page-size="form.pageSize"    :page-sizes="[10, 20, 30, 40,50,60,70,80,90,100]"
              layout="sizes, prev, pager, next"  :total="form.total">
      </el-pagination>
    </div>

    <el-drawer
      :title="dialogTitle"
      :visible.sync="isShowDialog"
      direction="ltr"
      custom-class="demo-drawer"
      ref="drawer"
      size="50%">
      <div class="demo-drawer__content">
        <div style="height: 80%;margin-top: 20px">
          <el-divider content-position="left"><span style="font-size: 20px;color: #1990FE">授权设备选择</span></el-divider>
          <el-card style="margin-top: 20px">
            <div class="page_filter">
              <el-button type="primary" @click="clearFilter">清除所有过滤条件</el-button>
              <p style="font-size: 12px;color: #ff4d51;line-height: 50px">点击表头的箭头可选择过滤条件,只能授权绑定了外壳且正常的设备</p>
            </div>
            <el-input
              v-model="searchCode"
              style="width: 40%"
              clearable
              placeholder="输入编号">
              <template slot="prepend">外壳编号</template>
            </el-input>
            <el-input
              v-model="searchSn"
              style="width: 40%;margin-left: 5%"
              clearable
              placeholder="输入SN">
              <template slot="prepend">设备SN</template>
            </el-input>
            <el-table height="450px" :data="tableAuth" border
                      ref="multipleTable"
                      tooltip-effect="dark">
              <el-table-column fixed width="55">
                <template slot-scope="scope">
                  <el-checkbox v-model="scope.row.select" @change="handleSelectionChange(scope.row.id)"></el-checkbox>
                </template>
              </el-table-column>
              <el-table-column label="序号" fixed width="80">
                <template slot-scope="scope">
                  {{getIndex(scope.$index)}}
                </template>
              </el-table-column>
              <el-table-column prop="caseCode" sortable label="设备编号" min-width="165">
              </el-table-column>
              <el-table-column prop="sn" sortable label="采集仪SN" min-width="165">
              </el-table-column>
              <el-table-column prop="equipName" sortable label="型号" width="120" :filters="filterList('equipName')"
                               :filter-method="filterHandler">
              </el-table-column>
              <el-table-column prop="batch" sortable label="批次" width="120" :filters="filterList('batch')"
                               :filter-method="filterHandler">
              </el-table-column>
              <el-table-column prop="holePosition" label="关联的传感器" width="120" align="center">
                <template slot-scope="scope">
                  <el-popover trigger="click" @show="showDevice(scope.row.sensorList)" placement="right">
                    <el-table :header-cell-style="{background:'#1990FE!important'}" border stripe :data="tableData"
                              style="width: 100%">
                      <el-table-column prop="code" label="编码" width="180">
                      </el-table-column>
                      <el-table-column prop="typeName" label="类型" width="100">
                      </el-table-column>
                    </el-table>
                    <div slot="reference" class="name-wrapper">
                      <i class="el-icon-data-analysis s-icon"></i>
                    </div>
                  </el-popover>
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </div>
        <div>
          <el-divider content-position="left"><span style="font-size: 20px;color: #1990FE">授权/出售单位选择</span></el-divider>
          <el-card style="margin-top: 20px;padding: 10px">
            <div style="display: inline-block">
              <label class="auth-unit" style="color:#1990FE">授权单位</label>
              <el-cascader :options="monitorUnitTree" ref="cascader" clearable v-model="selectedFromOptions"
                           change-on-select
                           placeholder="请选择授权单位" @change="selectFromUnit"></el-cascader>
            </div>
            <div style="display:inline-block;margin-left: 10px;">
              <label class="auth-unit" style="color:#1990FE;">出售单位</label>
              <el-select v-model="monitorForm.companyId" filterable clearable placeholder="请选择出售单位">
                <el-option v-for="item in companyList" :key="item.id" :label="item.name" :value="item.id">
                </el-option>
              </el-select>
            </div>
          </el-card>
        </div>
      </div>
      <div class="demo-drawer__footer">
        <span slot="footer" class="dialog-footer">
        <el-button class="common_btn-white" @click="isShowDialog = false">取消</el-button>
        <el-button class="common_btn-defalut" type="primary" @click="validateForm">确定</el-button>
      </span>
      </div>
    </el-drawer>

    <!-- 取消授权 -->
    <el-dialog title="取消设备授权" :visible.sync="isShowCancelDialog" :close-on-click-modal="false" width="520px">
      <!-- 具体form表单 -->
      <el-form label-position="right" ref="form" :model="currentRow" label-width="110px">
        <el-form-item label="设备状态" prop="testStatus">
          <el-radio-group v-model="currentRow.testStatus" @change="changeStatus">
            <el-radio-button label='3'>设备正常</el-radio-button>
            <el-radio-button label='4'>设备异常</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="情况描述" prop="explanation">
          <el-input v-model="currentRow.explanation" type="textarea"
                    :autosize="{ minRows: 4, maxRows: 6 }"
                    placeholder="描述设备情况"></el-input>
        </el-form-item>
      </el-form>
      <!-- 操作按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button class="common_btn-white" @click="isShowCancelDialog = false">取消</el-button>
        <el-button class="common_btn-defalut" type="primary" @click="submitCancel">确定</el-button>
      </span>
    </el-dialog>
    <!-- 详细信息弹窗 -->
    <el-dialog title="详细信息" :visible.sync="isShowDialogDetail" :close-on-click-modal="false" width="800px"
               class="s-dialog">
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>用户单位详细信息</span>
        </div>
        <div>
          <el-row :gutter="20">
            <el-col :span="6">
              <div class="grid-content">单位名称:</div>
            </el-col>
            <el-col :span="12">
              <div class="grid-content ">{{currentRow.authCustomer}}</div>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="6">
              <div class="grid-content">联系人:</div>
            </el-col>
            <el-col :span="12">
              <div class="grid-content ">{{currentRow.authContacts}}</div>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="6">
              <div class="grid-content">联系电话:</div>
            </el-col>
            <el-col :span="12">
              <div class="grid-content ">{{currentRow.authContactsTel}}</div>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="6">
              <div class="grid-content">详细地址:</div>
            </el-col>
            <el-col :span="12">
              <div class="grid-content ">{{currentRow.authAddress}}</div>
            </el-col>
          </el-row>
        </div>
      </el-card>
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>上位机详细信息</span>
        </div>
        <div>
          <el-row :gutter="20">
            <el-col :span="6">
              <div class="grid-content">SN:</div>
            </el-col>
            <el-col :span="12">
              <div class="grid-content ">{{currentRow.sn}}</div>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="6">
              <div class="grid-content">型号:</div>
            </el-col>
            <el-col :span="12">
              <div class="grid-content ">{{currentRow.equipName}}</div>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="6">
              <div class="grid-content">批次:</div>
            </el-col>
            <el-col :span="12">
              <div class="grid-content ">{{currentRow.batch}}</div>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="6">
              <div class="grid-content">授权时间:</div>
            </el-col>
            <el-col :span="12">
              <div class="grid-content ">{{currentRow.authTime | formatTimer}}</div>
            </el-col>
          </el-row>
        </div>
      </el-card>
      <p style="clear: both;"></p>
    </el-dialog>
    <x-loading v-show="isLoading"></x-loading>
  </div>
</template>
<script>
import {
  swjQueryList,
  deviceAuthList,
  deviceCancel,
  deviceAuth,
  getEquipType,
  companySelectQuery,
} from '@/services/model/sensor'
import Format from '@/utils/format'
import {getOrganizationTree} from "@/services/model/user";
import XLoading from '@/components/animation/x-loading.vue'

export default {
  components: {XLoading},
  data() {
    return {
      isLoading: false,
      // 型号下拉列表
      EnumEquipTypeList: [],
      selectedFromOptions: [],
      selectedSearchOptions: [],
      monitorUnitTree: [],
      //查询已授权表单
      form: {
        page: 1,
        pageSize: 10,
        testStatusList: '5,6',
        total: 0,
        modelId:'',
      },
      monitorForm: {
        authDeptTreeId: '',
        equipIdList: ''
      },
      // total: 0,
      totalDialog: 0,
      tableList: [],
      isShowDialog: false, // 是否显示弹窗
      isShowCancelDialog: false, // 是否显示弹窗
      isShowDialogDetail: false,
      currentRow: {}, // 新增数据
      tableData: [],
      tableDataAuth: [],
      multipleSelection: [],
      companyList: [],
      testStatus: 0,
      searchCode: '',
      searchSn: '',
    }
  },
  computed: {
    tableAuth() {
      let list = this.tableDataAuth
      if (this.searchCode && this.searchSn) {
        list = this.tableDataAuth.filter(data => data.caseCode.includes(this.searchCode) && data.sn.includes(this.searchSn))
      } else if (this.searchCode) {
        list = this.tableDataAuth.filter(data =>{
        if(data.caseCode){
       return    data.caseCode.includes(this.searchCode)
        }
        })
      } else if (this.searchSn) {
        list = this.tableDataAuth.filter(data => data.sn.includes(this.searchSn))
      }
      list.map(x => {
        x.select = false
        if (this.multipleSelection.indexOf(x.id) !== -1) {
          x.select = true
        }
      })
      return list
    },
    // 授权设备过滤选项去重
    filterList() {
      return function (field) {
        //整理选项
        let list = this.tableDataAuth.map(x => ({text: x[field], value: x[field]}))
        // 空obj，记录表
        let obj = {}
        //去重
        list = list.reduce((cur, next) => {
          //不包含才push
          if (!obj[next.value]) {
            obj[next.value] = cur.push(next)
          }
          return cur
        }, [])
        return list
      }
    },
    // 弹窗的title
    dialogTitle() {
      return this.currentRow.id ? '编辑传感器信息' : '设备授权'
    },
  },
  filters: {
    // 时间格式化
    formatTimer(timer) {
      if (timer) {
        return Format(new Date(timer))
      }
      return ''
    },
    equipStatusColor(val) {
      switch (val) {
        case 0:
          return 'background-color:#909399'
        case 1:
          return 'background-color:#0073b7'
        case 2:
          return 'background-color:#f39c12'
        case 3:
          return 'background-color:#0DC26B'
        case 4:
          return 'background-color:#e43321'
        default:
          return 'background-color:#03a9f4'
      }
    },
  },
  methods: {
    clearFilter() {
      this.$refs.multipleTable.clearFilter();
    },
    changeStatus() {
      this.$forceUpdate()
    },
    selectFromUnit() {
      this.$refs.cascader.dropDownVisible = false
    },
    async getMonitorUnit() {
      let res = await getOrganizationTree({unitType: 4})
      this.monitorUnitTree = res.data || []
    },
    // 隐藏表头选择框
    cellClass(row) {
      if (row.columnIndex === 0) {
        return 'DisabledSelection'
      }
    },
    // 获取当前的序号
    getIndex(index) {
      let param = (this.form.page - 1) * this.form.pageSize + index + 1
      return param
    },
    // 分页大小改变
    handleSizeChange(val) {
      this.form.pageSize = val
      this.queryList()
    },
    // 当前页码改变
    handleCurrentChange(val) {
      this.form.page = val
      this.queryList()
    },
    // 关联传感器显示
    async showDevice(val) {
      this.tableData = val
    },
    // 表单提交
    validateForm() {
      this.monitorForm.equipIdList = this.multipleSelection
      this.monitorForm.authDeptTreeId = this.selectedFromOptions.join('-')
      this.submitData()
    },
    async submitData() {
      // 根据ID判断使用新增还是编辑
      let res = await deviceAuth(this.monitorForm)
      if (res.code === 200) {
        this.$notify({
          type: 'success',
          title: '提示',
          message: '授权成功'
        })
        this.isShowDialog = false
        this.queryList()
        return true
      }
    },
    cancelAuth(row) {
      this.currentRow = {}
      this.currentRow.id = row.id
      this.currentRow.testStatus = '3'
      this.isShowCancelDialog = true
    },
    // 取消授权
    async submitCancel() {
      let res = await deviceCancel(this.currentRow)
      if (res.code === 200) {
        this.$notify({
          type: 'success',
          title: '提示',
          message: '取消授权成功'
        })
        this.isShowCancelDialog = false
        this.queryList()
      } else {
        this.$notify({
          type: 'error',
          title: '提示',
          message: '取消授权失败'
        })
      }
    },
    // 新增数据
    handleAdd() {
      this.queryListSearch()
      this.monitorForm = {}
      this.multipleSelection=[]
      this.selectedFromOptions = []
      this.isShowDialog = true
      this.$nextTick(() => {
        this.$refs.multipleTable.clearSelection()
      })
    },
    // 选择设备
    handleSelectionChange(val) {
      let index = this.multipleSelection.indexOf(val);
      if (index === -1) {
        this.multipleSelection.push(val)
      } else {
        this.multipleSelection.splice(index, 1)
      }
    },
    /**
     * row  当前操作行的对象
     */
    customerInfo(row) {
      this.isShowDialogDetail = true
      this.currentRow = JSON.parse(JSON.stringify(row))
    },
    // 首页列表
    async queryList() {
      this.isLoading = true
      this.form.authDeptTreeId = this.selectedSearchOptions.join('-')
      let res = await swjQueryList(this.form)
      this.tableList = res.data?.records || []
      this.form.page = Number(res.data?.current)
      this.form.total = Number(res.data?.total)
      this.isLoading = false
    },
    filterHandler(value, row, column) {
      const property = column.property
      return row[property] === value
    },
    async getEquipType() {
      let res = await getEquipType();
      this.EnumEquipTypeList = res.data ? res.data : []
      this.EnumEquipTypeList.map(x => {
        if (x.explanation.indexOf(',14,') !== -1||
          x.explanation.indexOf(',2,') !== -1) {
          x.disabled=true
        }else {
          x.disabled=false
        }
      })
    },
    //查询未授权表单
    async queryListSearch() {
      let res = await deviceAuthList()
      this.tableDataAuth = res.data || []
    },
    async getCompanyList() {
      // 监测单位查询
      let res = await companySelectQuery({companyType: '2,3'})
      this.companyList = res?.data || []
    }
  },
  mounted() {
    this.getEquipType();
  },
  activated() {
    this.getCompanyList()
    this.getMonitorUnit()
    this.queryList()
  }
}
</script>

<style lang="less" scoped>
  .demo-drawer__content {
    /deep/ .el-table th {
      padding: 0px 0;
      font-size: 13px;
    }

  }

  /deep/ .el-table th > .cell.highlight {
    color: #9cfd31;
  }

  /deep/ .el-table__column-filter-trigger i {
    color: #ffffff;
    font-size: 18px;
    font-weight: 600;
  }

  .clearfix {
    color: #000000;
  }

  .s-icon {
    cursor: pointer;
  }

  .s-icon:hover {
    color: #5cb6ff;
  }

  .s-select {
    float: left;
  }

  .s-dialog /deep/ .el-dialog__body {
    padding-top: 10px;
    padding-bottom: 10px;
  }

  .box-card {
    float: left;
    width: 45%;
    margin-left: 3%;
  }

  .el-row {
    line-height: 20px;
    margin-bottom: 15px;

    &:last-child {
      margin-bottom: 0;
    }

    .el-col:first-child {
      text-align: right;
    }

    .el-col:last-child {
      text-align: left;
    }
  }

  .auth-unit {
    float: left;
    margin-right: 20px;
    font-size: 20px;
    margin-top: 10px;
    color: #1990FE;
    font-weight: 600;
  }
</style>
